package www.gxw.com.uspserver.test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;

import www.gxw.com.uspserver.domain.Location;

/**
 * UDP服务类.
 * 
 * @author 晓炜
 *
 */
public class UdpServerSocket {

	/**
	 * heb相关
	 */
	private Configuration configuration;
	private SessionFactory factory;
	private Session session;
	// private Transaction tx;
	private Transaction tx;

	/**
	 * udp相关
	 */

	private byte[] buffer = new byte[1024];

	private DatagramSocket ds = null;

	private DatagramPacket packet = null;

	private InetSocketAddress socketAddress = null;

	private String orgIp;

	/**
	 * 构造函数，绑定主机和端口.
	 * 
	 * @param host
	 *            主机
	 * @param port
	 *            端口
	 * @throws Exception
	 */
	public UdpServerSocket(String host, int port) throws Exception {
		socketAddress = new InetSocketAddress(host, port);
		ds = new DatagramSocket(socketAddress);
		System.out.println("服务端启动!");
	}

	public final String getOrgIp() {
		return orgIp;
	}

	/**
	 * 设置超时时间，该方法必须在bind方法之后使用.
	 * 
	 * @param timeout
	 *            超时时间
	 * @throws Exception
	 */
	public final void setSoTimeout(int timeout) throws Exception {
		ds.setSoTimeout(timeout);
	}

	/**
	 * 获得超时时间.
	 * 
	 * @return 返回超时时间.
	 * @throws Exception
	 */
	public final int getSoTimeout() throws Exception {
		return ds.getSoTimeout();
	}

	/**
	 * 绑定监听地址和端口.
	 * 
	 * @param host
	 *            主机IP
	 * @param port
	 *            端口
	 * @throws SocketException
	 */
	public final void bind(String host, int port) throws SocketException {
		socketAddress = new InetSocketAddress(host, port);
		ds = new DatagramSocket(socketAddress);
	}

	/**
	 * 接收数据包，该方法会造成线程阻塞.
	 * 
	 * @return 返回接收的数据串信息
	 * @throws IOException
	 */
	public final String receive() throws IOException {
		packet = new DatagramPacket(buffer, buffer.length);
		ds.receive(packet);
		orgIp = packet.getAddress().getHostAddress();
		String info = new String(packet.getData(), 0, packet.getLength());
		System.out.println("接收信息：" + info);

		System.out.println("packet:" + packet);

		System.out.println("packet.getData:" + packet.getData());
		System.out.println("-----------------------");

		String byte2HexStr = CHexConver.byte2HexStr(packet.getData(),
				packet.getLength());
		String hexStr2Str = CHexConver.hexStr2Str(byte2HexStr);
		String str2HexStr = CHexConver.str2HexStr(info);
		String hexStr2Str2 = CHexConver.hexStr2Str(str2HexStr);
		byte[] byte2hexStr2Bytes = CHexConver.hexStr2Bytes(byte2HexStr);
		byte[] strhexStr2Bytes = CHexConver.hexStr2Bytes(str2HexStr);

		System.out.println("byte2HexStr:" + byte2HexStr);
		System.out.println();
		System.out.println("hexStr2Str:" + hexStr2Str);
		System.out.println();
		System.out.println("str2HexStr:" + str2HexStr);
		System.out.println();
		System.out.println("hexStr2Str2:" + hexStr2Str2);
		System.out.println();
		System.out.println("byte2hexStr2Bytes:X" + byte2hexStr2Bytes);
		System.out.println();
		System.out.println("strhexStr2Bytes:X" + strhexStr2Bytes);

		return info;
	}

	/**
	 * 将响应包发送给请求端.
	 * 
	 * @param bytes
	 *            回应报文
	 * @throws IOException
	 */
	public final void response(String info) throws IOException {
		System.out.println("客户端地址 : " + packet.getAddress().getHostAddress()
				+ ",端口：" + packet.getPort());
		DatagramPacket dp = new DatagramPacket(buffer, buffer.length,
				packet.getAddress(), packet.getPort());
		dp.setData(info.getBytes());
		ds.send(dp);
	}

	/**
	 * 设置报文的缓冲长度.
	 * 
	 * @param bufsize
	 *            缓冲长度
	 */
	public final void setLength(int bufsize) {
		packet.setLength(bufsize);
	}

	/**
	 * 获得发送回应的IP地址.
	 * 
	 * @return 返回回应的IP地址
	 */
	public final InetAddress getResponseAddress() {
		return packet.getAddress();
	}

	/**
	 * 获得回应的主机的端口.
	 * 
	 * @return 返回回应的主机的端口.
	 */
	public final int getResponsePort() {
		return packet.getPort();
	}

	/**
	 * 关闭udp监听口.
	 * 
	 */
	public final void close() {
		try {
			ds.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 测试方法.
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		String serverHost = "192.168.1.111";
		int serverPort = 3343;
		Location location = new Location();
		UdpServerSocket udpServerSocket = new UdpServerSocket(serverHost,
				serverPort);
		
		
		while (true) {
			Configuration configuration = new Configuration().configure();
			SessionFactory factory = configuration.buildSessionFactory();
			Session session = factory.openSession();
			// private Transaction tx;
			Transaction tx = session.beginTransaction();
			String receive = udpServerSocket.receive();

			System.out.println(udpServerSocket.getOrgIp());
			
			udpServerSocket.response(udpServerSocket.getOrgIp());

			location.setIp(udpServerSocket.getOrgIp());

			location.setPort(udpServerSocket.getResponsePort());

			System.out.println("receive:" + receive);
			
			String substring = receive.substring(5);
			System.out.println("substring:"+substring);
			
			String[] split = substring.split(",");
			for (int i = 0; i < split.length; i++) {
				System.out.println(i+" "+split[i]);
			}
			
			System.out.println("------------"+split[2]);
			
			String[] latsplit = split[2].split("\\.");
			String[] lonsplit = split[4].split("\\.");
			
			System.out.println(latsplit.length);
			
			for (int i = 0; i < latsplit.length; i++) {
				System.out.println(latsplit[i]);
			}
			
			int latInt = Integer.parseInt(latsplit[0]);
			int a = latInt/100;
			int b = latInt%100;
			System.out.println(a+"            "+b);
			
			System.out.println("00000"+latsplit[0]);
			
			String lat = new String(a+"."+b+latsplit[1]);
			System.out.println(lat);
			
			int lonInt = Integer.parseInt(lonsplit[0]);
			int lona = lonInt/100;
			int lonb = lonInt%100;
			
			String lon = new String(lona+"."+lonb+lonsplit[1]);
			System.out.println(lon);
			
			location.setLat(lat);
			location.setLon(lon);
/*
			JSONObject jsonObject = new JSONObject(receive);
			System.out.println("------" + udpServerSocket.getResponseAddress());
			location.setPort(udpServerSocket.getResponsePort());
			location.setLat(jsonObject.getString("lat").toString());
			location.setLon(jsonObject.getString("lon").toString());*/

			session.save(location);

			// System.out.println(jsonObject.get("lon").toString());
			tx.commit();
			session.close();
			factory.close();
		}

	}
}
